package com.example.experiment_3;

import android.content.Context;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileSaveLogin {

    public static void saveUserInfo(String account, String password, Context context) {
        String fileName = "user.txt";               // 文件名称
        String content = account + "\n" + password; // 保存数据
        FileOutputStream fos = null;
        try {
            fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            fos.write(content.getBytes());          // 将数据写入文件中
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();                    // 关闭输出流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT).show();
        }
    }

    public static void login(String account, String password, Context context) {
        String content;
        String storageAccount = "";
        String storagePassword = "";
        FileInputStream fis = null;
        try {
            fis = context.openFileInput("user.txt");    // 获得文件输入流对象
            byte[] buffer = new byte[fis.available()];  // 创建缓冲区, 并获取文件长度
            fis.read(buffer);                           // 将文件内容读取到buffer缓冲区
            content = new String(buffer);               // 转换成字符串
            String[] parts = content.split("\n");
            storageAccount = parts[0];
            storagePassword = parts[1];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();                        // 关闭输入流
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (account.equals(storageAccount) && password.equals(storagePassword)) {
                Toast.makeText(context, "登录成功!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "登录失败!", Toast.LENGTH_SHORT).show();
            }
        }
    }

}